package com.snopy.socket;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author snopy
 * @version 1.0.0
 * @classname EchoServer
 * @description 我们正在相互交谈.
 * @email 77912204@qq.com
 * @date 2022/08/01 14:19
 */
@Slf4j
public class EchoServer {
    public static void main(String[] args) {
        if (args.length!=1){
            log.error("Usage:java EchoServer <port number>");
            System.exit(1);
        }
        int portNumber = Integer.parseInt(args[0]);
        try (ServerSocket serverSocket = new ServerSocket(portNumber);
             Socket accept = serverSocket.accept();
             PrintWriter out = new PrintWriter(accept.getOutputStream(),true);
             BufferedReader in = new BufferedReader(new InputStreamReader(accept.getInputStream()));
        ){
            String outLine;
            while ((outLine = in.readLine())!=null){
                log.info("echo:{}",outLine);
                out.println(outLine);

            }

        } catch (IOException e) {
            log.error("Exception caught when trying to listen on port:{} or listening for a connection",portNumber);
            log.error(e.getMessage());
            //throw new RuntimeException(e);
        }
    }
}
